package heapdemo;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-09-11
 * Time: 16:09
 */

class ImpMaxComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
public class Test {

    public static int[] smallest(int[] arr, int k) {
        int[] array = new int[k];
        if(arr == null || k < 1) {
            return array;
        }

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }

        for (int i = k; i < arr.length; i++) {
            int a = priorityQueue.peek();
            if(a < arr[i]) {
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            array[i] = priorityQueue.poll();
        }
        return array;
    }

    public static int[] smallestK(int[] arr, int k) {
        int[] array = new int[k];
        if(arr == null || k < 1) {
            return array;
        }
        ImpMaxComparator impMaxComparator = new ImpMaxComparator();
        PriorityQueue<Integer> PriorityQueue = new PriorityQueue<>(impMaxComparator);
        //创建前k个数的小根堆
        for(int i = 0; i < k; i++) {
            PriorityQueue.offer(arr[i]);
        }
        //将剩下的数据跟头节点比较
        for(int i = k; i < arr.length; i++) {
            int a = PriorityQueue.peek();
            if(a > arr[i]) {
                PriorityQueue.poll();
                PriorityQueue.offer(arr[i]);
            }
        }
        //将前k个最小数放到数组里面
        for(int i = 0; i < k; i++) {
            array[i] = PriorityQueue.poll();
        }
        return array;
    }

    public static void main(String[] args) {
        int[] arr = {1,3,5,7,2,4,6,8};
        int[] array = smallest(arr,4);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }

    }
    public static void main2(String[] args) {
        ImpMaxComparator impMaxComparator = new ImpMaxComparator();
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(impMaxComparator);
        priorityQueue.offer(30);
        priorityQueue.offer(20);
        priorityQueue.offer(10);
        System.out.println(priorityQueue.peek());
        priorityQueue.poll();
    }

    public static void main1(String[] args) {
        int[] arr = {27,15,19,18,28,34,65,49,25,37};
        MyHeap myHeap = new MyHeap();
        myHeap.createHeap(arr);
        myHeap.createBigHeap();
        myHeap.offer(60);
    }
}
